package com.ruoyi.web.controller.app;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.novel.domain.Records;
import com.ruoyi.novel.service.IRecordsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 点赞收藏相关接口
 */

@RestController
@RequestMapping("/app/collect")
public class AppCollectController {

    @Autowired
    private IRecordsService recordsService;

    /**
     * 保存/取消 点赞收藏加入书架记录
     * @param records
     * @return
     */
    @PostMapping("/saveRecords")
    public AjaxResult saveRecords(@RequestBody Records records) {
        records.setUserId(Math.toIntExact(SecurityUtils.getUserId()));
        records.setCreateTime(new Date());

        QueryWrapper<Records> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",SecurityUtils.getUserId()).eq("type", records.getType());
        if(records.getVideoId() != null && records.getVideoId() > 0){
            queryWrapper.eq("video_id",records.getVideoId());
        }
        if(records.getFriendsId() != null && records.getFriendsId() > 0){
            queryWrapper.eq("friends_id",records.getFriendsId());
        }
        if(records.getCommunityId() != null && records.getCommunityId() > 0){
            queryWrapper.eq("community_id",records.getCommunityId());
        }
        if(records.getNovelId() != null && records.getNovelId() > 0){
            queryWrapper.eq("novel_id",records.getNovelId());
        }
        List<Records> recordsList = recordsService.list(queryWrapper);
        if(recordsList.isEmpty()){
            return AjaxResult.success("操作成功",recordsService.save(records));
        }else {
            List<Integer> ids = recordsList.stream().map(Records::getId).collect(Collectors.toList());
            return AjaxResult.success("取消成功", recordsService.removeBatchByIds(ids));
        }
    }
}
